<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 老猫 <thinkcmf@126.com>
// +----------------------------------------------------------------------
namespace app\portal\controller;

use cmf\controller\AdminBaseController;
use app\portal\model\PortalPostModel;
use app\portal\service\PostService;
use app\portal\model\PortalCategoryModel;
use think\Db;
use think\Image;
use app\wechat\controller\User;

//失物领取中心
class AdminMeetingBookController extends AdminBaseController
{   
    public function export(){
        $data   = $this->request->param();
        if (!empty($data['start_time']) && !empty($data['end_time'])) {
            $where['a.start_time'] = ['egt',strtotime($data['start_time'])];
            $where['a.end_time'] = ['elt',strtotime($data['end_time'])];
        }
        if (!empty($data['meet_id'])) {
            $where['a.meet_id'] = $data['meet_id'];
        }
        if (!empty($data['is_pay'])) {
            if($data['is_pay'] == 1){
                $where['a.end_type'] = 1;
            }elseif ($data['is_pay'] = 2) {
                $where['a.end_type'] = 0;
            }
        }
        $where['a.delete_time'] = ['eq',0];
        $log_list = Db::name('meeting_book')
            ->alias('a')
            ->join('member m','a.user_id=m.id')
            ->join('wechat_department_user b','m.openid=b.user_id')
            ->join('wechat_department c','c.id=b.department_id')
            ->join('meeting w','a.meet_id = w.id')
            ->field('a.*,w.list_title,w.in_price,w.out_price,m.user_login,m.mobile,c.name')
            ->where($where)
            ->order("a.start_time DESC")
            ->select();

        $str = 'ID,会议室,会议主题,会议人数,会议时间,预定部门,联系人,联系电话,备注,会议类型,是否需要纯净水,是否需要布置主席台,对内参考价格,对外参考价格,实际结算价格,预定状态,取消状态,支付状态'."\n";
        $str = iconv('utf-8','gb2312//TRANSLIT',$str);
        $string = '';
        $type = ['0'=>"未选择",'1'=>"彩排",'2'=>"会议",'3'=>"演出",'4'=>"布场"];
        $status = ['0'=>"不需要",'1'=>"需要"];
        $shenhe = ['0'=>"未审核",'1'=>"已通过",'2'=>'未通过'];
        $cancel = ['0'=>"未取消",'1'=>"已取消",'2'=>'已申请取消'];
        $pay = ['0'=>"未交会场费",'1'=>"已交会场费"];
        for ($i=0,$counts=count($log_list); $i < $counts; $i++) { 
            $csv[] = iconv('utf-8','gb2312//TRANSLIT',$log_list[$i]['id']);
            $csv[] = iconv('utf-8','gb2312//TRANSLIT',$log_list[$i]['list_title']);
            $csv[] = iconv('utf-8','gb2312//TRANSLIT',$log_list[$i]['theme']);
            $csv[] = iconv('utf-8','gb2312//TRANSLIT',$log_list[$i]['num']);
            $time = date('Y-m-d H:00:00',$log_list[$i]['start_time'])."至".date('Y-m-d H:00:00',$log_list[$i]['end_time']);
            $csv[] = iconv('utf-8','gb2312//TRANSLIT',$time);
            $csv[] = iconv('utf-8','gb2312//TRANSLIT',$log_list[$i]['name']);
            $csv[] = iconv('utf-8','gb2312//TRANSLIT',$log_list[$i]['user_login']);
            $csv[] = iconv('utf-8','gb2312//TRANSLIT',$log_list[$i]['mobile']);
            $csv[] = iconv('utf-8','gb2312//TRANSLIT',$log_list[$i]['remark']);
            
            $csv[] = iconv('utf-8','gb2312//TRANSLIT',$type[$log_list[$i]['type']]);
            $csv[] = iconv('utf-8','gb2312//TRANSLIT',$status[$log_list[$i]['is_water']]);
            $csv[] = iconv('utf-8','gb2312//TRANSLIT',$status[$log_list[$i]['is_layout']]);
            $in = (($log_list[$i]['end_time']-$log_list[$i]['start_time'])/3600)*$log_list[$i]['in_price'];
            $out = (($log_list[$i]['end_time']-$log_list[$i]['start_time'])/3600)*$log_list[$i]['out_price'];
            $csv[] = iconv('utf-8','gb2312//TRANSLIT',$in);
            $csv[] = iconv('utf-8','gb2312//TRANSLIT',$out);
            $csv[] = iconv('utf-8','gb2312//TRANSLIT',$log_list[$i]['price']);
            $csv[] = iconv('utf-8','gb2312//TRANSLIT',$shenhe[$log_list[$i]['status']]);
            $csv[] = iconv('utf-8','gb2312//TRANSLIT',$cancel[$log_list[$i]['cancel']]);
            $csv[] = iconv('utf-8','gb2312//TRANSLIT',$pay[$log_list[$i]['end_type']]);
            $string .= implode(",",$csv)."\n";
            unset($csv);
        }
        $filename = "会议预定列表_".date('YmdHis').'.csv'; //设置文件名
        header("Content-type:text/csv"); 
        header("Content-Disposition:attachment;filename=".$filename); 
        header('Cache-Control:must-revalidate,post-check=0,pre-check=0'); 
        header('Expires:0'); 
        header('Pragma:public'); 
        echo $str.$string;
    }

    //列表
    public function index(){

        $data   = $this->request->param();
        if (!empty($data['start_time']) && !empty($data['end_time'])) {
            $where['a.start_time'] = ['egt',strtotime($data['start_time'])];
            $where['a.end_time'] = ['elt',strtotime($data['end_time'])];
        }
        if (!empty($data['meet_id'])) {
            $where['a.meet_id'] = $data['meet_id'];
        }
        if (!empty($data['is_pay'])) {
            if($data['is_pay'] == 1){
                $where['a.end_type'] = 1;
            }elseif ($data['is_pay'] = 2) {
                $where['a.end_type'] = 0;
            }
        }
        $where['a.delete_time'] = ['eq',0];
        $log_list = Db::name('meeting_book')
            ->alias('a')
            ->join('member m','a.user_id=m.id','left')
            ->join('wechat_department_user b','m.openid=b.user_id','left')
            ->join('wechat_department c','c.id=b.department_id','left')
            ->join('meeting w','a.meet_id = w.id','left')
            ->field('a.*,w.list_title,w.in_price,w.out_price,m.user_login,m.mobile,c.name')
            ->where($where)
            ->order("a.start_time DESC")
            ->paginate(10);

        $user = Db::name('member')->column('id,user_login,mobile');
        $this->assign('user',$user);
        $department = Db::name('wechat_department')->column('id,name');
        $this->assign('department',$department);

        $meet = Db::name('meeting')->select();
        $this->assign('meet',$meet);
        // 获取分页显示
        $page = $log_list->render();
       
        $this->assign("page", $page);
  
        $this->assign("data", $log_list);
        return $this->fetch();
    }
    //添加页面
    public function add(){
        $log_list = Db::name('meeting')->select();
        $this->assign('meet',$log_list);

        $content = '区纪委监委、区委办公室、区委组织部、区委宣传部、区委统战部、区委政法委、区编委办公室、区直属机关党委、区信访局、区府办公室、区财政局、区招商办、琶洲管委会、区机关事务局、区人大、区政协、区总工会、团区委、区妇联、区侨联';
        $content = explode('、',$content);
        $ids = [];
        $arr = [];
        foreach($content as $k => $v){
            $ids[$k]  = Db::name('wechat_department')->where('name','like','%'.$v.'%')->column('id,name');
            $arr[array_keys($ids[$k])[0]] = array_values($ids[$k])[0];
        }
        $this->assign('part',$arr);

        $log_list = Db::name('meeting')->select();
        $this->assign('meet',$log_list);

        return $this->fetch();
    }
    //查询部门用户
    public function usercheck(){
        $id = $this->request->param('id',0,'intval');
        //$id = 300000016;

        $ids = Db::name('wechat_department_user')->where('department_id',$id)->column('user_id');
        $name = Db::name('member')->where('openid','in',$ids)->column('id,user_login');
        echo json_encode(array('msg'=>$name,'id'=>$id));return;
        //return $name;
    }
    //添加提交
    public function addPost()
    {   
        
        if ($this->request->isPost()) {
            $data   = $this->request->param();
            $post   = $data['post'];
            
   
            if (empty($post['theme'])) {
                $this->error("会议主题不能为空！");
            } 
            if ( !is_numeric($post['num']) || $post['num'] <= 0 ) {
                $this->error("会议人数必须大于0！");
            }
            $post['start_time'] = strtotime(date("Y-m-d H:00:00",strtotime($post['start_time'])));
            $post['end_time'] = strtotime(date("Y-m-d H:00:00",strtotime($post['end_time'])));
            if ( $post['start_time'] < time() ) {
                $this->error("会议开始时间必须晚于当前时间！(时间自动忽略分秒)");
            }
            if ( $post['start_time'] >= $post['end_time']  ) {
                $this->error("会议结束时间必须晚于会议开始时间！(时间自动忽略分秒)");
            }
            $timewhere = ['gt',time()];
            $book_info = Db::name('meeting_book')->where(['meet_id'=>$post['meet_id'],'start_time'=>$timewhere])->select();
            for ($i=0,$count = count($book_info); $i < $count; $i++) { 
                if ( ($post['start_time'] >= $book_info[$i]['start_time']) && ($post['start_time'] < $book_info[$i]['end_time']) ) {
                    $this->error("会议时间与其他会议时间有冲突，请检查！(时间自动忽略分秒)");
                }
                if (($post['start_time'] <= $book_info[$i]['start_time']) && ($post['end_time'] >= $book_info[$i]['end_time'])) {
                    $this->error("会议时间与其他会议时间有冲突，请检查！(时间自动忽略分秒)");
                }
            }
            /*$pattern = '/^\d+(\.\d+)?$/';
            if(!preg_match($pattern,$post['price'])){
                $this->error("价格必须填数字！");
            }*/
            $post['status'] = 1;
            $post['time'] = time();
            $res = Db::name('meeting_book')->insertGetId($post);
            if ($res) {
                $meeting_info = Db::name('meeting')->where(['id'=>$post['meet_id']])->find();
                //操作日志
                admin_log($meeting_info['list_title'], 'add', '预定会议室');
                Db::name('new_msg')->insert(
                    [
                        'table_name'=>'meeting_book',
                        'time'=>time(),
                        'department_id'=> $post['department_id'],
                        'content'=> $meeting_info['list_title']."预约",
                        'object_id'=>$res,
                        'user_id'=>$post['user_id'],
                        'type'=>4
                    ]);
                $info = Db::name('meeting_book')
                ->alias('a')
                ->join('cmf_member b','a.user_id=b.id')
                ->where(['a.id'=>$id])
                ->value('b.openid');

                $meet = Db::name('meeting')->find($post['meet_id']);
                try {
                    $user = new User();

                    $descr = "<div class=\"normal\">温馨提示：您预约的".date('Y-m-d H:00',$post['start_time'])."至".date('H:00',$post['end_time']).$$meet['list_title']."已通过审核，请按时到场使用会场，咨询请致电89088693、89088642。</div>";

                    $url = url('portal/meeting/book','','html',true);

                
                    @$user->send($info,'会场预约',$descr,$url);
                } catch (Exception $e) {
                    return true;
                }
                

                $this->success('添加成功!', url('AdminMeetingBook/index'));
            }else{
                $this->error('添加失败');
            }
            
        }

    }
    //编辑
    public function edit(){
        $id = $this->request->param('id', 0, 'intval');
        $data = Db::name('meeting_book')->find($id);
        $log_list = Db::name('meeting')->select();


        $content = '区纪委监委、区委办公室、区委组织部、区委宣传部、区委统战部、区委政法委、区编委办公室、区直属机关党委、区信访局、区府办公室、区财政局、区招商办、琶洲管委会、区机关事务局、区人大、区政协、区总工会、团区委、区妇联、区侨联';
        $content = explode('、',$content);
        $ids = [];
        $arr = [];
        foreach($content as $k => $v){
            $ids[$k]  = Db::name('wechat_department')->where('name','like','%'.$v.'%')->column('id,name');
            $arr[array_keys($ids[$k])[0]] = array_values($ids[$k])[0];
        }
        $this->assign('part',$arr);

        $ids = Db::name('wechat_department_user')->where('department_id',$data['department_id'])->column('user_id');
        $user = Db::name('member')->where('openid','in',$ids)->column('id,user_login');
        $this->assign('user',$user);

        $this->assign('meet',$log_list);
        $this->assign('result',$data);
        return $this->fetch();
    }
    //编辑提交
    public function editPost(){

        if ($this->request->isPost()) {
            $data   = $this->request->param();
            $post   = $data['post'];
            
   
            if (empty($post['theme'])) {
                $this->error("会议主题不能为空！");
            } 
            if ( !is_numeric($post['num']) || $post['num'] <= 0 ) {
                $this->error("会议人数必须大于0！");
            }
            $post['start_time'] = strtotime(date("Y-m-d H:00:00",strtotime($post['start_time'])));
            $post['end_time'] = strtotime(date("Y-m-d H:00:00",strtotime($post['end_time'])));
            if ( $post['start_time'] < time() ) {
                $this->error("会议开始时间必须晚于当前时间！(时间自动忽略分秒)");
            }
            if ( $post['start_time'] >= $post['end_time']  ) {
                $this->error("会议结束时间必须晚于会议开始时间！(时间自动忽略分秒)");
            }
            $timewhere = ['gt',time()];
            $book_info = Db::name('meeting_book')->where(['meet_id'=>$post['meet_id'],'cancel'=>['neq',1],'start_time'=>$timewhere,'id'=>['neq',$post['id']]])->select();
            for ($i=0,$count = count($book_info); $i < $count; $i++) { 
                if ( ($post['start_time'] >= $book_info[$i]['start_time']) && ($post['start_time'] < $book_info[$i]['end_time']) ) {
                    $this->error("会议时间与其他会议时间有冲突，请检查！(时间自动忽略分秒)");
                }
                if (($post['start_time'] <= $book_info[$i]['start_time']) && ($post['end_time'] >= $book_info[$i]['end_time'])) {
                    $this->error("会议时间与其他会议时间有冲突，请检查！(时间自动忽略分秒)");
                }
            }
            /*$pattern = '/^\d+(\.\d+)?$/';
            if(!preg_match($pattern,$post['price'])){
                $this->error("价格必须填数字！");
            }*/
            $post['status'] = 1;
            $post['time'] = time();
            $res = Db::name('meeting_book')->where(['id'=>$post['id']])->update($post);
            if ($res) {
                $meeting_info = Db::name('meeting')->where(['id'=>$post['meet_id']])->find();
                //操作日志
                admin_log($meeting_info['title'], 'edit', '预定会议室');

                $this->success('编辑成功!', url('AdminMeetingBook/index'));
            }else{
                $this->error('编辑失败');
            }
            
        }

    }
    //删除提交
    public function delete(){
        $param   = $this->request->param();
        if (isset($param['id'])) {
            $id   = $this->request->param('id', 0, 'intval');
            $data = Db::name('meeting_book')->find($id);
            $res = Db::name('meeting_book')->where(['id'=>$id])->update(['delete_time'=>time()]);
            if ($res) {
                $data   = [
                    'object_id'   => $data['id'],
                    'create_time' => time(),
                    'table_name'  => 'meeting_book',
                    'name'        => $data['theme'],
                    'site_id'     => 1,  //站点ID
                ];
                Db::name('recycleBin')->insert($data);
            
                //操作日志
                admin_log($data['name'], 'delete', '会议室预定');

                $this->success('删除成功!', url('AdminMeetingBook/index'));
            }else{
                $this->error('删除失败');
            }
        }
    }
    //通过审核提交
    public function go(){
        $param   = $this->request->param();
        if (isset($param['id'])) {
            $id   = $this->request->param('id', 0, 'intval');
            $data = Db::name('meeting_book')->find($id);
            $res = Db::name('meeting_book')->where(['id'=>$id])->update(['status'=>1]);
            if ($res) {
                //操作日志
                admin_log($data['name'], 'edit', '会议预定通过审核');

                $this->success('审核成功!', url('AdminMeetingBook/index'));
            }else{
                $this->error('审核失败');
            }
        }
    }
    //审核
    public function shenhe(){
        $id   = $this->request->param('id', 0, 'intval');
        $res = Db::name('meeting_book')->where(['id'=>$id])->find();
        $this->assign('meet_book',$res);
        return $this->fetch();
    }
    //审核提交
    public function shenhePost(){
        $param   = $this->request->param();
        if (isset($param['id'])) {
            $id   = $this->request->param('id', 0, 'intval');
            $res = Db::name('meeting_book')->where(['id'=>$id])->update($param);
            if ($res) {

                $data = Db::name('meeting')->where(['id'=>$res['meet_id']])->find();
                $book_info = Db::name('meeting_book')
                ->alias('a')
                ->join('meeting t','a.meet_id=t.id','left')
                ->join('member m','a.user_id=m.id','left')
                ->join('wechat_department_user b','m.openid=b.user_id','left')
                ->join('wechat_department c','c.id=b.department_id','left')
                ->field('a.id,c.name,m.user_login,a.theme,a.user_id,a.start_time,a.end_time,t.list_title,m.openid')
                ->where(['a.id'=>$id])->find();
                //操作日志
                Db::name('new_msg')->insert(
                    [
                        'table_name'=>'meeting_book',
                        'time'=>time(),
                        'department_id'=> 0,
                        'content'=> $book_info['list_title']."预约",
                        'object_id'=>$id,
                        'user_id'=>$book_info['user_id'],
                        'type'=>4
                    ]);

                $admin = Db::name('wechat_tag_user')
                ->where('tagid',config('meet'))
                ->column('userid');

                $meet_admin = implode("|",$admin);
                
                    $user = new User();
                    if($param['status'] == 2){
                        $descr = "<div class=\"normal\">温馨提示：您预约的".date('Y-m-d H:00',$book_info['start_time'])."至".date('H:00',$book_info['end_time']).$book_info['list_title']."未通过审核，请重新预约其他时间段的会场，如有疑问请致电89088693、89088642。</div>";

                    }elseif ($param['status'] == 1) {
                        $descr = "<div class=\"normal\">温馨提示：您预约的".date('Y-m-d H:00',$book_info['start_time'])."至".date('H:00',$book_info['end_time']).$book_info['list_title']."已通过审核，请按时到场使用会场，咨询请致电89088693、89088642。</div>";
                    }
                    
                    $url = url('portal/meeting/book','','html',true);

                    $descr2 = "<div class=\"normal\">温馨提示：".$book_info['name'].$book_info['user_login']."预约的".date('Y-m-d H:00',$book_info['start_time'])."至".date('H:00',$book_info['end_time']).$book_info['list_title']."，订单号：".$book_info['id']."已通过审核，请查看订单提前做好会场布置。</div>";

                try {
                    @$user->send($meet_admin,'会场预约',$descr2,$url);

                    @$user->send($book_info['openid'],'会场预约',$descr,$url);
                } catch (Exception $e) {
                    return true;
                }
                
                admin_log($data['name'], 'edit', '会议预定审核成功');

                $this->success('审核成功!');
            }else{
                $this->error('审核失败');
            }
        }
    }
    //结算
    public function end(){
        return $this->fetch();
    }
    //结算提交
    public function endPost(){
        $param   = $this->request->param();
        if (isset($param['id'])) {
            $id   = $this->request->param('id', 0, 'intval');
            $param['end_type'] = 1;
            $res = Db::name('meeting_book')->where(['id'=>$id])->update($param);
            if ($res) {

                $book_info = Db::name('meeting_book')
                ->alias('a')
                ->join('meeting t','a.meet_id=t.id','left')
                ->join('member m','a.user_id=m.id','left')
                ->join('wechat_department_user b','m.openid=b.user_id','left')
                ->join('wechat_department c','c.id=b.department_id','left')
                ->field('a.id,c.name,m.user_login,a.theme,a.user_id,a.start_time,a.end_time,t.list_title,m.openid')
                ->where(['a.id'=>$id])
                ->find();
                try {
                
                    $user = new User();
                    $url = url('portal/meeting/book','','html',true);

                    $descr = "<div class=\"normal\">温馨提示：".$book_info['name'].$book_info['user_login']."使用的".date('Y-m-d H:00',$book_info['start_time'])."至".date('H:00',$book_info['end_time']).$book_info['list_title']."，订单号：".$book_info['id']." 费用已结算，请问您是否满意本次服务，您的意见将是我们前进的最大动力！</div>";
                    @$user->send($book_info['openid'],'会场预约',$descr,$url);
                } catch (Exception $e) {
                    return true;
                }
                
                admin_log($book_info['theme'], 'edit', '会议预定结算成功');

                $this->success('结算成功!');
            }else{
                $this->error('结算失败');
            }
        }
    }
    //取消页面
    public function cancel(){
        $id   = $this->request->param('id', 0, 'intval');
        $res = Db::name('meeting_book')->where(['id'=>$id])->find();
        $this->assign('meet_book',$res);
        return $this->fetch();
    }
    //取消提交
    public function cancelPost(){
        $param   = $this->request->param();
        $id   = $this->request->param('id', 0, 'intval');
        $res = Db::name('meeting_book')->where(['id'=>$id])->update(['cancel'=>$param['cancel']]);
        if ($res) {
            if ($param['cancel'] == 1) {
                $user = new User();
                $book_info = Db::name('meeting_book')
                ->alias('a')
                ->join('meeting t','a.meet_id=t.id','left')
                ->join('member m','a.user_id=m.id','left')
                ->join('wechat_department_user b','m.openid=b.user_id','left')
                ->join('wechat_department c','c.id=b.department_id','left')
                ->field('a.id,c.name,m.user_login,a.theme,a.user_id,a.start_time,a.end_time,t.list_title,m.openid')
                ->where(['a.id'=>$id])->find();

                $url = url('portal/meeting/book','','html',true);
                try {
                    $admin = Db::name('wechat_tag_user')
                    ->where('tagid',config('meet'))
                    ->column('userid');

                    $meet_admin = implode("|",$admin);

                    $descr = "<div class=\"normal\">温馨提示：".$book_info['name'].$book_info['user_login']."使用的".date('Y-m-d H:00',$book_info['start_time'])."至".date('H:00',$book_info['end_time']).$book_info['list_title']."申请取消预约已通过，订单号：".$book_info['end_time']."。</div>";

                    

                    $descr = "<div class=\"normal\">温馨提示：".$book_info['name'].$book_info['user_login']."使用的".date('Y-m-d H:00',$book_info['start_time'])."至".date('H:00',$book_info['end_time']).$book_info['list_title']."已取消，订单号：".$book_info['end_time']."。</div>";
                    
                    @$user->send($book_info['openid'],'会场预约',$descr,$url);
                    @$user->send($meet_admin,'会场预约',$descr2,$url);
                } catch (Exception $e) {
                    return true;
                }
                
            }
            //操作日志
            admin_log($book_info['list_title'], 'edit', '会议预定取消成功');

            $this->success('审核成功!');
        }else{
            $this->error('审核失败');
        }
    }
}
